import axios from 'axios'
import ElementUI from 'element-ui';
import qs from 'qs';
import router from '@/router'

/****************************************
    创建用于get,post请求的Axios实例
***************************************/
const service1 = axios.create({
  baseURL:"http://api.diandu.com/index.php/",//process.env.API_SERVER, //config.xx.env.js中配置
  timeout: 15000,
});
service1.interceptors.request.use(config => {
  const token = localStorage.getItem("token");
  config.headers["Token"] = token == null ? "" : token;
  if (config.method == 'post') {
    //config.headers["Content-Type"]='application/x-www-url-encoded';
    config.data = qs.stringify(config.data);
  }
  return config;
}, error => {
  //console.error("发送请求出错",error);
   return Promise.reject(error);
})

service1.interceptors.response.use(
  response => {
    var {status,data} = response;
      return response;
    },
  error => {
    return Promise.reject(error);
  });


/****************************************
    创建用于文件上传的Axios实例
***************************************/
const service2 = axios.create({
  timeout: 25000,
  baseURL:process.env.API_SERVER,
  headers: {
    "Content-Type": "multipart/form-data"
  }
});
service2.interceptors.request.use(config => {
  //Header中携带其他信息
  if (localStorage.getItem("token") != null) {
    config.headers['token'] = localStorage.getItem("token");
  }
  return config;
});
service2.interceptors.response.use(
    response =>{
      return response;
    }
  , error => {
      return Promise.reject(error);
});



/****************************************
       统一封装一下get,post,upload
****************************************/

export const request = {
  get(url, data) {
    return new Promise((resolve, reject) => {
      service1.get(url,data).then((response) => {
       if (response.status === 200 ) {
          resolve(response.data);
        } else {
          reject(response.data);
        }
      }).catch((err) => {
        reject(err);
      });
    })
  },
  post(url, data) {
    return new Promise((resolve, reject) => {
      service1.post(url, data).then((response) => {
        const {config,data,headers,status}=response;
        if (response.status === 200 ) {
          switch(response.data.code){
            case 401:
             ElementUI.Message({message:"登录超时或无权访问,请重新登录!",type:"error"});
             resolve(response.data);
            break;
          }
          resolve(response.data);
        } else {
          reject(response.data);
        }
      }).catch((err) => {
        reject(err);
      });
    })
  },
  upload(url, data) {
    return new Promise((resolve,reject)=>{
      service2.post(url,data).then((response)=>{
          if (response.status === 200) {
            resolve(response.data);
          } else {
            reject(response.data);
          }
      }).catch((err)=>{
          reject(err);
      });
    })
  }
}
